package abacab.remote.netty;

import java.io.ByteArrayInputStream;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import abacab.remote.Connection;
import abacab.remote.ConnectionRegistry;
import abacab.remote.protocol.MessageProtocol;

/**
 * The decoder for received messages
 */
public class MessageDecoder extends OneToOneDecoder {
	/** The logger */
	private static final Logger				logger	= LoggerFactory.getLogger(MessageDecoder.class);

	/** The connection registry */
	private final ConnectionRegistry	registry;

	/** The connection */
	private final Connection					connection;

	/**
	 * Create the decoder
	 * 
	 * @param registry
	 *          the connection registry
	 * @param connection
	 *          the connection
	 */
	public MessageDecoder(ConnectionRegistry registry, Connection connection) {
		this.registry = registry;
		this.connection = connection;
	}

	@Override
	protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
		ChannelBuffer message;
		try {
			message = (ChannelBuffer) msg;
		}
		catch (ClassCastException e) {
			logger.warn("Unknown type of message: " + msg.getClass().getName(), e);
			return msg;
		}
		ByteArrayInputStream bais = new ByteArrayInputStream(message.array());
		return MessageProtocol.decode(bais, this.registry.getSerilizationExt(), this.connection);
	}
}